package cn.javasea.rbac.shiro.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * 通过账号名称生成对应的token令牌
 * @author xiangchao
 * @date 2023/2/1 21:16
 */
public class JwtUtil {

    private static final String secret = "secret";

    /**
     * 创建token
     */
    public static String createToken(String username, Long expiration) {
        Date expireDate = new Date(expiration);
        String token = JWT.create()
                .withClaim("username", username)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 校验token是否正确
     */
    public static boolean verify(String token, String username) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("username", username)
                .build();
        verifier.verify(token);
        return true;
    }

    /**
     * 解析token，获取用户名
     */
    public static String getUsername(String token) {
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("username").asString();
    }

}
